package com.xx.landing;

import javafx.animation.Interpolator;
import javafx.animation.RotateTransition;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.util.Duration;

import java.util.function.Supplier;

import static com.xx.util.Util.getResourceUrl;

public class LoadingButton {
    public static void butLoading(javafx.scene.control.Button button, Supplier<Boolean> supplier) {
        Node graphic = button.getGraphic();
        button.setDisable(true);//Disable
        RotateTransition rotate;//旋转动画
        ImageView loadingView = new ImageView(new Image(getResourceUrl("/texture/loading.png")));
        loadingView.setFitHeight(20);
        loadingView.setFitWidth(20);
        //动画属性
        rotate = new RotateTransition(Duration.millis(500), loadingView);
        rotate.setFromAngle(360);
        rotate.setToAngle(0);
        rotate.setCycleCount(Timeline.INDEFINITE);//次数：无数次
        rotate.setInterpolator(Interpolator.LINEAR);//：每次旋转完的过渡:均匀过渡
        rotate.play();
        button.setGraphic(loadingView);
        Thread thread = new Thread(() -> {
            if (supplier.get()) {//加载完成
                Platform.runLater(() -> {
                    button.setGraphic(graphic);//停止动画
                    button.setDisable(false);//Disable
                });
            }
        });
        thread.start();
    }
}
